/* eslint-disable jsdoc/no-restricted-syntax */
// 实现一个 Promise.all 方法

/**
 * @param {(Promise<any> | unknown)[]} promises
 * @returns {Promise<(any | Promise<any>)[]>}
 */
export const all = (promises) => {
  if (promises.length === 0) {
    return Promise.resolve([]);
  }
  return new Promise((resolve, reject) => {
    /**
     * @type {any[]}
     */
    const results = [];
    let count = 0;
    for (const promise of promises) {
      if (promise instanceof Promise) {
        promise
          // eslint-disable-next-line no-loop-func
          .then((res) => {
            results.push(res);
            count++;

            if (count === promises.length) {
              resolve(results);
            }
          })
          .catch(reject);
      } else {
        results.push(promise);
        count++;
        if (count === promises.length) {
          resolve(results);
        }
      }
    }
  });
};
